package com.fjec.devops.schedule.handler;

import com.fjec.common.schedule.BaseScheduleHandler;
import com.fjec.common.util.DateUtil;
import com.fjec.common.util.JsonUtil;
import com.fjec.devops.feign.MarketClient;
import com.fjec.devops.service.IBizYsOfflineRegService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class YsOffLineRegHandler extends BaseScheduleHandler {

    @Resource
    private IBizYsOfflineRegService ysOfflineRegService;

    @Resource
    private MarketClient marketClient;

    public String handle(int days) {
        List<Map<String, Object>> errorList = new ArrayList<>();
        // 计算日期
        List<LocalDateTime> dateList = DateUtil.computeBeforeDateList(days, 1);
        List<String> strDateList = new ArrayList<>();
        for (LocalDateTime date : dateList) {
            try {
                String dateTime = DateUtil.format(date, "yyyy-MM-dd");
                strDateList.add(dateTime);
                // 查询这一天文件是否已生成
                boolean isHandle = ysOfflineRegService.dateIsHandled(date.toLocalDate());
                if (!isHandle) {
                    List<Map<String, Object>> dataList = marketClient.getOffLineRegList(dateTime);
                    if (dataList != null && !dataList.isEmpty()) {
                        ysOfflineRegService.uploadExcels(date.toLocalDate(), dateTime, dataList);
                    }
                }
            } catch (Exception ex) {
                String guid = this.error(ex);
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("guid", guid);
                errorMap.put("dateTime", DateUtil.format(date, "yyyy-MM-dd"));
                errorList.add(errorMap);
            }
        }
        String result;
        if (errorList.isEmpty()) {
            // 全部处理，无异常
            result = String.format("Handle ys offline reg success. Days: %s", JsonUtil.toJson(strDateList));
        } else {
            result = String.format("Handle ys offline reg fault: %s", JsonUtil.toJson(errorList));
        }
        return result;
    }

}
